package com.example.new5.views;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.new5.R;
import com.example.new5.adapter.HotsearchAdapter;
import com.example.new5.entity.Hotsearch;
import com.example.new5.utils.JsonUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;

public class HotsearchFragment extends Fragment {
    private RecyclerView recyclerView;

    public HotsearchFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hotsearch, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 解析JSON并填充数据
        List<Hotsearch> hotsearchList = parseJsonToHotsearchData(getJson("hotsearch.json"));
        HotsearchAdapter adapter = new HotsearchAdapter(hotsearchList);
        recyclerView.setAdapter(adapter);
        return view;
    }
    private List<Hotsearch> parseJsonToHotsearchData(String jsonStr) {
        List<Hotsearch> hotsearchList = new ArrayList<>();
        JsonObject jsonObject = JsonParser.parseString(jsonStr).getAsJsonObject();
        JsonArray result = jsonObject.getAsJsonArray("result");
        for (JsonElement jsonElement : result) {
            JsonObject hotsearchObject = jsonElement.getAsJsonObject();
            String title = hotsearchObject.get("title").getAsString();
            Integer index = hotsearchObject.get("index").getAsInt();
            String hotValue = hotsearchObject.get("hotValue").getAsString();
            String link = hotsearchObject.get("link").getAsString();
            hotsearchList.add(new Hotsearch(title, index, hotValue, link));
        }
        return hotsearchList;
    }
    private String getJson(String name) {
        String json = JsonUtils.getJsonFromAssets(getContext(), name);
        Log.d("asdf", "getJson = " + json);
        return json;
    }
}